package org.agpsoft.simpledatareceiver;
import java.io.IOException;
import java.io.InputStream;

import org.agpsoft.datareceiverinfrastructure.common.RawData;
import org.agpsoft.datareceiverinfrastructure.datasource.IDataAccessor;
import org.agpsoft.datareceiverinfrastructure.exception.DataReceiverAccessException;
import org.agpsoft.datareceiverinfrastructure.exception.DataReceiverCloseException;
import org.agpsoft.datareceiverinfrastructure.exception.DataReceiverException;
import org.agpsoft.datareceiverinfrastructure.exception.DataReceiverNULLObjectException;
import org.agpsoft.datareceiverinfrastructure.exception.DataReceiverOpenException;
import org.agpsoft.datareceiverinfrastructure.facade.IDataReceiverProcessor;

public class SimpleDataAccessor implements IDataAccessor {
	
	private InputStream inStream = null;
	private IDataReceiverProcessor processor = null;
	
	@Override
	public void requestDataFromSource(int dataLength)
			throws DataReceiverException {
		
		RawData readData = new RawData( new byte[dataLength] );
		
		if( inStream == null )
		{
			throw new DataReceiverAccessException();
		}else
		{
			try {
				readData.setActiveDataLength( 
						inStream.read( readData.getData(), 0, readData.getData().length ) );
				processor.processData( readData );
			} catch (IOException e) {
				throw new DataReceiverAccessException();
			}
		}
	}
	

	@Override
	public void close() throws DataReceiverCloseException {
	}

	@Override
	public void open( Object context ) throws DataReceiverOpenException {
		SimpleDataReceiverContext basicDataReceiverContext = 
			(SimpleDataReceiverContext) context;
		inStream = basicDataReceiverContext.getInputStream();
	}

	@Override
	public void setDataProcessor(IDataReceiverProcessor processor)
			throws DataReceiverNULLObjectException {
		this.processor = processor;
	}
}
